package com.study.talk.module.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class NettyServer {

    @Value("${netty.port}")
    private Integer port;

    @Autowired
    private TalkServerInitializer initializer;

    private ServerBootstrap bootstrap;

    private NioEventLoopGroup boss;

    private NioEventLoopGroup worker;

    private Channel channel;

    private void open() throws Exception {
        bootstrap = new ServerBootstrap();
        boss = new NioEventLoopGroup();
        worker = new NioEventLoopGroup();

        ChannelFuture channelFuture = bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(initializer)
                .bind(port)
                .sync();
        log.info("netty服务启动成功，端口：{}", port);
        channel = channelFuture.channel();

        //关闭监听服务
        channel.closeFuture().sync();
    }

    public synchronized void start() {
        try {
            open();
        } catch (Exception e) {
            close();
        }

    }

    private synchronized void close() {
        log.info("netty服务关闭");
        try {
            if (channel != null) {
                channel.close();
            }
        } catch (Throwable e) {
            log.warn(e.getMessage(), e);
        }
        try {
            if (bootstrap != null) {
                boss.shutdownGracefully();
                worker.shutdownGracefully();
            }
        } catch (Throwable e) {
            log.warn(e.getMessage(), e);
        }
        log.info("netty服务成功关闭");
    }

}
